import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_im_demo/model/friend_model.dart';
import 'package:flutter_im_demo/state/global_state.dart';
import 'package:flutter_im_demo/widget/loading_widget.dart';
import 'package:flutter_im_demo/widget/navigation_widget.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';
import '../const_value.dart';
import 'package:cached_network_image/cached_network_image.dart';

import 'add_friend_page.dart';
import 'chat_page.dart';

const divider = Divider();

const _suspensionHeight = 20;
const _itemHeight = 60;

class FriendListPage extends StatelessWidget {
  const FriendListPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
          title: Text(appTitle),
          actions: <Widget>[
            IconButton(
              icon: Icon(FontAwesomeIcons.search, size: iconSize),
              onPressed: () {},
            ),
            IconButton(
              icon: Icon(FontAwesomeIcons.plus, size: iconSize),
              onPressed: () =>
                  showSearch(context: context, delegate: searchBarDelegate()),
            )
          ],
          flexibleSpace: Container(
            decoration: BoxDecoration(gradient: gradientColor),
          )),
      body: Consumer<GlobalState>(
          builder: (context, state, _) => state.isLogin
              ? (state.isLoading
                  ? LoadingWidget()
                  : AzListView(
                      data: state.friendList,
                      itemBuilder: (context, model) {
                        final f = model as Friend;
                        return FriendItemWidget(
                          key: Key(f.id),
                          friend: f,
                          state: state,
                        );
                      },
                      isUseRealIndex: true,
                      itemHeight: _itemHeight,
                      suspensionHeight: _suspensionHeight,
                      header: AzListViewHeader(
                          height: 0,
                          builder: (context) {
                            return Container();
                          }),
                      indexBarBuilder: (BuildContext context, List<String> tags,
                          IndexBarTouchCallback onTouch) {
                        return Container(
                          margin: EdgeInsets.symmetric(
                              vertical: 16.0, horizontal: 8.0),
                          decoration: BoxDecoration(
                              color: Colors.grey[50],
                              borderRadius: BorderRadius.circular(20.0),
                              border: Border.all(
                                  color: Colors.grey[300], width: .5)),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(20.0),
                            child: IndexBar(
                              data: tags,
                              itemHeight: 20,
                              onTouch: (details) {
                                onTouch(details);
                              },
                            ),
                          ),
                        );
                      },
                      indexHintBuilder: (context, hint) {
                        return Container(
                          alignment: Alignment.center,
                          width: 70.0,
                          height: 70.0,
                          decoration: BoxDecoration(
                            color: Colors.grey[500].withAlpha(200),
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          child: Text(hint,
                              style: TextStyle(
                                  color: Colors.white, fontSize: 40.0)),
                        );
                      },
                    ))
              : const NavigationWidget()),
    );
  }
}

class FriendItemWidget extends StatelessWidget {
  final Friend friend;
  final GlobalState state;

  const FriendItemWidget({Key key, this.friend, this.state}) : super(key: key);

  Widget _buildSusWidget(String susTag) {
    return Container(
      padding: EdgeInsets.only(left: 20.0),
      height: _suspensionHeight.toDouble(),
      width: double.infinity,
      color: Colors.grey[100],
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        style: TextStyle(fontSize: 12.0, color: Colors.black54),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Offstage(
          offstage: friend.isShowSuspension != true,
          child: _buildSusWidget(friend.getSuspensionTag()),
        ),
        SizedBox(
          height: _itemHeight.toDouble(),
          child: ListTile(
            onTap: () {
              toChatPageInitState(state, friend);
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return ChatPage(friend: friend, myId: state.userInfoModel.id);
              }));
            },
            key: Key(friend.id),
            leading: MyCircleAvatar(
                height: 40.0, avatar: friend.avatar, tag: friend.id),
            title: Text(
              (friend.note != null && friend.note.isNotEmpty)
                  ? friend.note
                  : friend.nickName,
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
            ),
          ),
        ),
      ],
    );
  }
}

void toChatPageInitState(GlobalState state, Friend friend) {
  final f = state.getFriend();
  state.setFriend(friend);
  if (f == null) {
    state.queryHistoryMessage();
  }

  // 如果有新消息，则点击的时候去掉该标记
  state.updateRemoveNewMessageFlag(friend);
}

class MyCircleAvatar extends StatelessWidget {
  final double height;
  final String avatar;
  final String tag;

  const MyCircleAvatar({Key key, this.height, this.avatar, this.tag})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Hero(
        tag: tag,
        child: CircleAvatar(
          radius: height / 2,
          backgroundImage: (avatar == null || avatar.isEmpty)
              ? AssetImage(
                  "assets/image/avatar.jpeg",
                )
              : CachedNetworkImage(
                  imageUrl: avatar,
                  fit: BoxFit.cover,
                  height: height,
                  width: height,
                ),
        ));
  }
}

/// insert into im_user_info (id, avatar, phone, nickName, note, city, token, expirationTime)
/// values (?,?,?,?,?,?,?,?)
//I/flutter ( 4726):   ' args [34e5b1935227463a9b736622a5d53ddd, , 18866259537, 王学鹏, , 青岛, 110, 1565937752]}
